import axios from "axios";
import store from "@/store";
import { isCheckTimeout } from "@/utils/auth";
import { ElMessage } from "element-plus";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
});

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      if (isCheckTimeout()) {
        store.dispatch("user/logout");
        return Promise.reject(new Error("token 失效"));
      }
      config.headers.Authorization = `Bearer ${store.getters.token}`;
    }
    config.headers.icode = "4B36864498A9DE88";
    // 配置接口国际化
    config.headers['Accept-Language'] = store.getters.language
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { success, message, data } = response.data;
    //   要根据success的成功与否决定下面的操作
    if (success) {
      return data;
    } else {
      // 业务错误
      ElMessage.error(message); // 提示错误消息
      // 再返回对应的错误消息
      return Promise.reject(new Error(message));
    }
  },
  // 请求失败
  (error) => {
    // 处理 token 过期
    if (
      error.response &&
      error.response.data &&
      error.response.data.code === 401
    ) {
      // 退出登录动作
      store.dispatch("user/logout");
    }
    ElMessage.error(error.message); // 提示错误信息
    return Promise.reject(error);
  }
);

export default service;
